//
//  HTSearchHistoryView.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/7.
//

import SwiftUI

struct HTSearchHistoryView: View {

  @EnvironmentObject private var var_store: HTAppStore

  @State var var_historyStrs: [String] = []
  var var_selCallback: ((String) -> Void)?

  var body: some View {
    ScrollView(.vertical, showsIndicators: false) {
      if (var_historyStrs.count > 0) {
        HStack{
          Text("History")
            .font(.system(size: 14))
            .fontWeight(.bold)
          Spacer()
          Button {
            var_store.dispatch(HTEnumSearchAction.ht_deleteAllSearchHistory())
            var_historyStrs = []
          } label: {
            Image("delete")
          }
          .padding(5)
        }
        .padding(.horizontal, 15)
        .padding(.vertical, 10)
          
          // 搜索历史
        HTFlexibleView(
          var_data: var_historyStrs,
          var_spacing: 15,
          var_alignment: .leading
        ) { item in
          HTTagView(var_name: item, var_nameSize: 12, var_padding: EdgeInsets(top: 6, leading: 16, bottom: 6, trailing: 16))
            .clipShape(Capsule())
            .onTapGesture {
              var_selCallback!(item)
            }
        }
        .padding(.horizontal, 15)
      }
        // 受欢迎的
        Group {
            Text("Popular")
              .font(.system(size: 14))
              .fontWeight(.bold)
              .padding(.leading, 15)
              .padding(.top, 20)
              .padding(.bottom, 10)
              .frame(maxWidth: .infinity, alignment: .leading)

            LazyVGrid(columns: [GridItem(.adaptive(minimum: (UIDevice.ht_screenWidth() - 40) / 2, maximum: .infinity))], spacing: 10) {
              ForEach(0..<(var_store.state.var_searchState.var_populars ?? []).count, id: \.self) {index in
                let var_color = index < 3 ? "#FF6C3C" : "#999999"
                let var_num: String = index < 9 ? "0\(index+1)" : "\(index+1)"
                let popular = (var_store.state.var_searchState.var_populars ?? [])[index]

                HTPopularItem(var_numTitle: var_num, var_numTitleColor: Color(hex: var_color), var_name: popular.var_title ?? "")
                  .frame(maxWidth: .infinity, alignment: .leading)
                  .padding(.top, 10)
                  .onTapGesture {
                    var_selCallback!(popular.var_title ?? "")
                  }
              }
            }
            .padding(.horizontal, 15)
        }
    }
    .frame(maxWidth: .infinity)
    .padding(.bottom, UIDevice.ht_safeDistanceBottom())
    .background(Color(hex: "#f5f5f5"))
    .onAppear{
      var_store.dispatch(HTEnumSearchAction.ht_searchHistoryList(callback: { result in
        var_historyStrs = result
      }))
    }
  }
}
